package com.ship.dispatch.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.Page;
import com.ship.common.core.domain.R;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.poi.ExcelUtil;
import com.ship.common.core.validate.Add;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.*;
import com.ship.dispatch.bean.fob.SpFobFileRecord;
import com.ship.dispatch.bean.fob.SpFobJsfhccbItems;
import com.ship.dispatch.bo.SmShipCrewImportBo;
import com.ship.dispatch.bo.TzFuelReportSumBo;
import com.ship.dispatch.bpm.vo.dto.BGTableDto;
import com.ship.dispatch.service.*;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 燃油台账加油记录 前端控制器
 *
 * @author zhangyh
 * @since 2024-01-10
 */
@RestController
@RequestMapping("/fuel/report")
@Api(value = "tzFuelReport", tags = "燃油台账加油记录前端控制器")
public class TzFuelReportController {

    @Autowired
    private TzFuelReportService tzFuelReportService;

    @Resource
    private RemoteFileService remoteFileService;

    @Value("${file_server.host}")
    private String fileServerHost;

    /**
     * 燃油台账加油记录汇总查询
     *
     * @return
     */
    @ApiOperation(value = "燃油台账加油记录汇总查询")
    @PostMapping(value = "/summary/list")
    public JsonResult<List<TzFuelReportSumBo>> getSummaryList(@RequestBody TzFuelReport dto) {
        return tzFuelReportService.getSummaryList(dto);
    }

    /**
     * 燃油台账加油记录汇总导出
     *
     * @return
     */
    @ApiOperation(value = "燃油台账加油记录汇总导出")
    @PostMapping(value = "/summary/export")
    public JsonResult exportSummaryList(@RequestBody TzFuelReport dto) throws IOException {
        JsonResult<List<TzFuelReportSumBo>> dataListR = tzFuelReportService.getSummaryList(dto);
        if(dataListR.getResultCode() != JsonResult.success().getResultCode()){
            return dataListR;
        }
        List<TzFuelReportSumBo> dataList = dataListR.getResultObject();
        //创建临时文件
        String fileName = "燃油台账-" + DateFormatUtils.format(new Date(), "yyyy-MM-dd")+".xlsx";
        File tempFile = new File(fileName);
        EasyExcel.write(fileName, TzFuelReportSumBo.class).sheet("加油汇总").doWrite(dataList);
        FileInputStream input = new FileInputStream(tempFile);
        MultipartFile multipartFile = new MockMultipartFile("file",tempFile.getName() , "application/octet-stream", input);
        R<SysFile> result1 = remoteFileService.upload(multipartFile);
        if(result1.getCode() != R.SUCCESS){
            tempFile.delete();
            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
        }
        String urls = result1.getData().getHttpsUrl();
        tempFile.delete();
        return JsonResult.success(urls);
    }

    /**
     * 加油记录新增
     *
     * @return
     */
    @ApiOperation(value = "加油记录新增")
    @PostMapping(value = "/add")
    @Log(title = "加油记录新增",businessType = BusinessType.INSERT)
    public JsonResult add(@RequestBody @Validated(Add.class) TzFuelReport dto) {
        return tzFuelReportService.add(dto);
    }

    /**
     * 加油记录编辑
     *
     * @return
     */
    @ApiOperation(value = "加油记录编辑")
    @PostMapping(value = "/update")
    @Log(title = "加油记录编辑",businessType = BusinessType.UPDATE)
    public JsonResult update(@RequestBody TzFuelReport dto) {
        return tzFuelReportService.dataUpdate(dto);
    }

    /**
     * 加油记录删除
     *
     * @return
     */
    @ApiOperation(value = "加油记录删除")
    @GetMapping(value = "/delete/{id}")
    @Log(title = "加油记录删除",businessType = BusinessType.DELETE)
    public JsonResult delete(@PathVariable(value = "id") Long id) {
        return tzFuelReportService.dataDelete(id);
    }


    /**
     * 加油记录分页
     *
     * @return
     */
    @ApiOperation(value = "加油记录分页")
    @PostMapping(value = "/page")
    public JsonResult<Page<TzFuelReport>> getPage(@RequestBody TzFuelReport dto) {
        Page<TzFuelReport> resultPage = tzFuelReportService.page(dto,new QueryWrapper<>());
        return JsonResult.success(resultPage);
    }

    /**
     * 加油记录导出
     *
     * @return
     */
    @ApiOperation(value = "加油记录导出")
    @PostMapping(value = "/export")
    public JsonResult export(@RequestBody TzFuelReport dto) throws IOException {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(dto.getIds() != null && dto.getIds().size() > 0){
            queryWrapper.in("id",dto.getIds());
        }
        List<TzFuelReport> dataList = tzFuelReportService.pageExportList(dto,queryWrapper,new LinkedList<>());

        String fileName = dto.getShipName()+"-加油记录-"+ DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        //创建临时文件
        File tempFileExcel = new File(fileName+".xlsx");
        EasyExcel.write(fileName+".xlsx", TzFuelReport.class).sheet("加油记录").doWrite(dataList);

        List<File> downloadFiles = new LinkedList<>();
        downloadFiles.add(tempFileExcel);

        //创建临时压缩文件
        File zipFile = new File(fileName+".zip");
        for (TzFuelReport tzFuelReport : dataList) {
            if(StringUtils.isBlank(tzFuelReport.getFilePathInfo())){
                continue;
            }
            String[] filePathArr = tzFuelReport.getFilePathInfo().split(",");
            for (String s : filePathArr) {
                String CsoldPart = "http://10.75.34.224:9300/statics";
                String ZsoldPart = "http://10.75.33.149:9300/statics";
                String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
                String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";

                String newUrl = "";
                if (s.contains("https://lngshipping.cgp.cnooc")) {
                    newUrl = s.replace(ZsPart, ZsoldPart);
                }else if (s.contains("https://lngshippingcs.cgp.cnooc")){
                    newUrl = s.replace(CsPart, CsoldPart);
                }else {
                    newUrl = s;
                }
                //文件下载进压缩包
                URL otherUrl = new URL(newUrl);
                InputStream otherInputStream = otherUrl.openStream();
                int spIndex = s.lastIndexOf(".");
                File tempFile = File.createTempFile(tzFuelReport.getShipName()+"-"+tzFuelReport.getFuelTime()+"-附件信息", s.substring(spIndex));
                try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = otherInputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, bytesRead);
                    }
                }
                downloadFiles.add(tempFile);
            }
        }
        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zos = new ZipOutputStream(fos)) {
            for (File downloadFile : downloadFiles) {
                ZipEntry zipEntry = new ZipEntry(downloadFile.getName());
                zos.putNextEntry(zipEntry);
                try (FileInputStream fis = new FileInputStream(downloadFile)) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, length);
                    }
                }
                zos.closeEntry();
                downloadFile.delete();
            }
        }
        FileInputStream input = new FileInputStream(zipFile);
        MultipartFile multipartFile = new MockMultipartFile("file", zipFile.getName(), "application/octet-stream", input);
        R<SysFile> result1 = remoteFileService.upload(multipartFile);
        if(result1.getCode() != R.SUCCESS){
            zipFile.delete();
            tempFileExcel.delete();
            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
        }
        String urls = result1.getData().getHttpsUrl();
        zipFile.delete();
        tempFileExcel.delete();
        return JsonResult.success(urls);
    }

}
